<template>
	<md-editor :preview="false"
			   :toolbars="allToolbars"
			   v-model="form.content"
			   style="height: 180px"
			   :onGetCatalog="fun"
			   @onUploadImg="onUploadImg"
	/>
	<md-editor
		v-model="form.content"
		style="text-align-all: left"
		preview-only
		@onHtmlChanged="onHtmlChange"
	/>
</template>

<script lang="ts" setup>
import {reactive, ref} from "vue";
import MdEditor, {HeadList} from 'md-editor-v3';
import axios from "axios";
import dayjs from "dayjs";
import request from "@/utils/request";


const allToolbars = [
	'bold',
	'underline',
	'italic',
	'-',
	'title',
	'strikeThrough',
	'sub',
	'sup',
	'quote',
	'unorderedList',
	'orderedList',
	'-',
	'link',
	'image',
	'-',
	'revoke',
	'next',
	'save',
	'=',
	'pageFullscreen',
	'fullscreen',
	'preview',
	'catalog',
];
const fun = (l: HeadList[]) => {
	l.forEach((i) => console.log(i.text));
}

const form = reactive({
	// 动态标题
	title: '',
	// 动态内容
	content: '',
	// 动态缩略图, 以第一张图片为准, 否则是头像
	banner: '',
	// 动态预览, 前50个字, 超过的话加上'...'
	summary: ''
	// 预想还有个目录, 懒得
})

const htmlText = ref('');

const onHtmlChange = (h: string) => {
	htmlText.value = h;
}

const onUploadImg = async (files: (string | Blob)[], callback: (arg0: any[]) => void) => {
	const res = await Promise.all(
		files.map((file: string | Blob) => {
			console.log(1.1);
			return new Promise((rev, rej) => {
				const form = new FormData();
				form.append('file', file);
				let upload_token = "null";
				form.append("fileName", new Date().getTime().toString());
				request.get("/dynamic/action/getUploadToken").then((res) => {
					upload_token = res.data;
					form.append("token", upload_token);
					axios.post('https://up-z2.qiniup.com', form, {
						headers: {
							'Content-Type': 'multipart/form-data'
						}
					})
						.then((res) => rev(res))
						.catch((error) => rej(error));
				});
			});
		})
	);
	callback(res.map((item: any) => "http://riwc83tf2.hn-bkt.clouddn.com/" + item.data.key));
};


// const text = ref("## 😲 md-editor-v3\n");

const create = () => {
	const summaryReg = /(?<=>)[^<>]+(?=<)/;
	const bannerReg = /(?<=!\[]\().+?(?=\))/;
	form.banner = bannerReg.exec(form.content)?.[0] ?? '';
	form.summary = htmlText.value.match(summaryReg)?.join() ?? '';
}

</script>

<style scoped>

</style>